package app.qrcode.browser.ykpixabay.ui.star

import android.widget.Toast
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import app.qrcode.browser.ykpixabay.MyApplication.Companion.context
import app.qrcode.browser.ykpixabay.logic.model.Hits
import cn.leancloud.LCObject
import cn.leancloud.LCQuery
import cn.leancloud.LCUser
import cn.leancloud.types.LCNull
import io.reactivex.Observer
import io.reactivex.disposables.Disposable


/**
 * Created by YiGo on 2022/4/21.
 */
class StarViewModel : ViewModel() {

    private val _dataListLive = MutableLiveData<List<LCObject>>()
    val dataListLive: LiveData<List<LCObject>>
        get() = _dataListLive

    private val _singleObjectIdList = MutableLiveData<List<String>>()
    val singleObjectIdList: LiveData<List<String>>
        get() = _singleObjectIdList


    init {
        updateStar()
    }

    fun updateStar() {
        val query = LCQuery<LCObject>("Star")
        query.whereEqualTo("user", LCUser.getCurrentUser())
        query.findInBackground().subscribe(object : Observer<List<LCObject>> {
            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: List<LCObject>) {
                _dataListLive.value = t
            }

            override fun onError(e: Throwable) {
                Toast.makeText(context, "${e.message}", Toast.LENGTH_SHORT).show()
            }

            override fun onComplete() {
            }

        })
    }
//        val liveQuery = LCLiveQuery.initWithQuery(query)
//        liveQuery.subscribeInBackground(object : LCLiveQuerySubscribeCallback() {
//            override fun done(e: LCException?) {
//            }
//
//        })
//        liveQuery.setEventHandler(object : LCLiveQueryEventHandler() {
//            override fun onObjectCreated(LCObject: LCObject) {
//                super.onObjectCreated(LCObject)
//                val t = _dataListLive.value?.toMutableList()
//                t?.add(LCObject)
//                _dataListLive.value = t
//            }
//
//            override fun onObjectDeleted(objectId: String?) {
//                super.onObjectDeleted(objectId)
//                val t = _dataListLive.value?.toMutableList()
//                val ob = t?.find {
//                    it.get("objectId") == objectId
//                }
//                t?.remove(ob)
//                _dataListLive.value = t
//            }
//
//            override fun onObjectUpdated(LCObject: LCObject, updateKeyList: MutableList<String>) {
//                super.onObjectUpdated(LCObject, updateKeyList)
//                val ob = _dataListLive.value?.find {
//                    it.get("objectId") == LCObject.get("objectId")
//                }
//                updateKeyList.forEach {
//                    ob?.put(it, LCObject.get(it))
//                }
//                _dataListLive.value = _dataListLive.value
//            }
//        })

    fun addItem(newItem: Hits) {
        LCObject("Star").apply {
            put("user", LCUser.getCurrentUser())
            put("tags", newItem.tags)
            put("webformatURL", newItem.webformatURL)
            put("largeImageURL", newItem.largeImageURL)
            put("id", newItem.id)
            saveInBackground().subscribe(object : Observer<LCObject> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: LCObject) {
                    Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show()
                    updateStar()
                }

                override fun onError(e: Throwable) {
                    Toast.makeText(context, "${e.message}", Toast.LENGTH_SHORT).show()
                }

                override fun onComplete() {
                }

            })
        }
    }

    fun deleteOneItem(objectId: String) {
        LCObject.createWithoutData("Star", objectId).apply {
            deleteInBackground().subscribe(object : Observer<LCNull?> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: LCNull) {

                }

                override fun onError(e: Throwable) {
                    Toast.makeText(context, "${e.message}", Toast.LENGTH_SHORT).show()
                }

                override fun onComplete() {
                    Toast.makeText(context, "取消收藏成功", Toast.LENGTH_SHORT).show()
                    updateStar()
                }

            })
        }
    }

    fun change(dataList: List<LCObject>, starList: MutableList<Hits>) {
        starList.clear()
        dataList.forEach {
            starList.add(
                Hits(
                    it.getString("tags"),
                    it.getString("webformatURL"),
                    it.getString("largeImageURL"),
                    it.getString("id")
                )
            )

        }
    }

    fun queryItem(id: String) {
        val query = LCQuery<LCObject>("Star")
        query.whereEqualTo("id", id)
        query.whereEqualTo("user", LCUser.getCurrentUser())
        query.findInBackground().subscribe(object : Observer<List<LCObject>> {
            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: List<LCObject>) {
                val objectIdList = mutableListOf<String>()
                t.forEach {
                    objectIdList.add(it.objectId)
                }
                _singleObjectIdList.value = objectIdList
            }

            override fun onError(e: Throwable) {
                Toast.makeText(context, "请检查网络", Toast.LENGTH_SHORT).show()
            }

            override fun onComplete() {

            }

        })
    }


    fun querySelectedItem(id: String, deleteObjectId: HashMap<String,String>) {
        val query = LCQuery<LCObject>("Star")
        query.whereEqualTo("id", id)
        query.whereEqualTo("user", LCUser.getCurrentUser())
        query.findInBackground().subscribe(object : Observer<List<LCObject>> {
            override fun onSubscribe(d: Disposable) {
            }

            override fun onNext(t: List<LCObject>) {
                t.forEach {
                    deleteObjectId[id] = it.objectId
                }
            }

            override fun onError(e: Throwable) {
                Toast.makeText(context, "请检查网络", Toast.LENGTH_SHORT).show()
            }

            override fun onComplete() {

            }

        })
    }



}